package admin;

import java.io.IOException;
import java.net.MalformedURLException;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.ffpc.sql.ConnectionFactory;

/**
 * A servlet that manages the initialization and cleanup of the application.
 * 
 * This servlet is designed to be loaded by the servlet container during application 
 * startup. Simply declare it in web.xml and give it the lowest load-on-startup value.
 * It must be loaded before all other servlets.
 * 
 * @author KENNETHLCH
 *
 */
public class LifecycleManager extends GenericServlet {
    
    private Logger logger = LogManager.getLogger(LifecycleManager.class);

    @Override
	public void service(ServletRequest arg0, ServletResponse arg1)
            throws ServletException, IOException {
        // This servlet does not serve any requests.
    }

    @Override
	public void destroy() {
        ConnectionFactory.shutdown();
    }

    @Override
	public void init() throws ServletException {
        try {
            String configFile = getServletConfig().getInitParameter("config");
            ConnectionFactory.initialize(new PropertiesConfiguration(getServletContext().getResource(configFile)));
        } catch (ConfigurationException e) {
            logger.error("Failed to load application config", e);
            throw new ServletException("Failed to load application config", e);
        } catch (MalformedURLException e) {
            // not likely
            logger.error("", e);
            throw new ServletException(e);
        }
    }

}
